package cn.shengchao.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.base.enums.ProductType;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeOrderTask;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeOrderTaskLogService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeOrderTaskService;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeOrderDomainService;
import cn.shengchao.examstar.pay.acl.adapters.repositories.OrderRepository;
import cn.shengchao.examstar.pay.infrastructure.dao.PayOrderItemDao;
import cn.shengchao.examstar.pay.infrastructure.dao.po.PayOrderItem;
import cn.shengchao.examstar.pay.model.entity.OrderEntity;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeOrderContentDto;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeOrderTaskStatusDataStatusEnum;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @program: examstarapi
 * @description: 分销任务的加载处理
 * @author: Xiong weiqiang
 * @create: 2025-04-21 17:22
 */
@Component
public class DistributeOrderTaskProcessJob {
    @Autowired
    DistributeOrderTaskService distributeOrderTaskService;
    @Autowired
    DistributeOrderDomainService distributeOrderDomainService;
    @Autowired
    DistributeOrderTaskLogService distributeOrderTaskLogService;
    @Autowired
    PayOrderItemDao payOrderItemDao;
    @Autowired
    OrderRepository orderRepository;
    @JobExecutor(name = "DistributeOrderTaskProcessJob")
    public void processTask(JobArgs jobArgs) {
        SnailJobLog.REMOTE.info("开始定时处理订单分销结算任务" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        long startTime = System.currentTimeMillis();
        List<DistributeOrderTask> distributeOrderTasks =distributeOrderTaskService.list(Wrappers.lambdaUpdate(DistributeOrderTask.class)
                .lt(DistributeOrderTask::getDistributeTime,new Date()).eq(DistributeOrderTask::getDataStatus,0).orderByAsc(DistributeOrderTask::getLastTaskTime).last("limit 10"));
        SnailJobLog.REMOTE.info("订单分销结算任务数量：" + distributeOrderTasks.size());
        if (CollUtil.isNotEmpty(distributeOrderTasks)){
            for (DistributeOrderTask distributeOrderTask : distributeOrderTasks) {
                Long taskId = distributeOrderTask.getId();
                Long orderId = distributeOrderTask.getOrderId();
                distributeOrderTaskService.update(Wrappers.lambdaUpdate(DistributeOrderTask.class)
                        .set(DistributeOrderTask::getDataStatus, DistributeOrderTaskStatusDataStatusEnum.STATUS_INASGN.getStatus()).eq(DistributeOrderTask::getId, taskId).set(DistributeOrderTask::getLastTaskTime,new Date()));

                if (ProductType.PRODUCT_MEMBER.name().equals(distributeOrderTask.getProductType())){
                    distributeOrderDomainService.processMemberDistributeOrderTask(taskId, orderId);
                }else if (ProductType.PRODUCT_THIRD_YCBDC.name().equals(distributeOrderTask.getProductType())){
                    OrderEntity orderEntity= orderRepository.queryOrder(orderId.toString());
                    distributeOrderDomainService.processThirdProductDistributeOrderTask(taskId, orderId,orderEntity.getProductId());
                }else if (ProductType.PRODUCT_THIRD_CAP.name().equals(distributeOrderTask.getProductType())){
                    OrderEntity orderEntity= orderRepository.queryOrder(orderId.toString());
                    distributeOrderDomainService.processThirdProductDistributeOrderTask(taskId, orderId,orderEntity.getProductId());
                }else if (ProductType.COURSE.name().equals(distributeOrderTask.getProductType())||ProductType.COURSE_NODES.name().equals(distributeOrderTask.getProductType())){
                    List<PayOrderItem> payOrderItems = payOrderItemDao.selectList(Wrappers.lambdaQuery(PayOrderItem.class)
                            .eq(PayOrderItem::getOrderId, orderId));
                    OrderEntity orderEntity= orderRepository.queryOrder(orderId.toString());
                    if (CollUtil.isNotEmpty(payOrderItems)) {
                        List<DistributeOrderContentDto> orderContentDtoList = payOrderItems.stream()
                                .map(a -> DistributeOrderContentDto.builder()
                                        .productId(a.getProductId())
                                        .productName(a.getProductName())
                                        .productAmount(a.getTotalAmount())
                                        .orderId(a.getOrderId())
                                        .orderTime(orderEntity.getOrderTime())
                                        .build())
                                .toList();
                        distributeOrderDomainService.processContentDistributeOrderTask(taskId, orderId, orderContentDtoList);
                    } else {
                        distributeOrderTaskLogService.logError(taskId, orderId, "订单创建任务监听，订单商品为空");
                    }
                }else {
                    List<PayOrderItem> payOrderItems = payOrderItemDao.selectList(Wrappers.lambdaQuery(PayOrderItem.class)
                            .eq(PayOrderItem::getOrderId, orderId));
                    OrderEntity orderEntity= orderRepository.queryOrder(orderId.toString());
                    if (CollUtil.isNotEmpty(payOrderItems)) {
                        List<DistributeOrderContentDto> orderContentDtoList = payOrderItems.stream()
                                .map(a -> DistributeOrderContentDto.builder()
                                        .productId(a.getProductId())
                                        .productName(a.getProductName())
                                        .productAmount(a.getTotalAmount())
                                        .orderTime(orderEntity.getOrderTime())
                                        .orderId(a.getOrderId())
                                        .build())
                                .toList();
                        distributeOrderDomainService.processContentDistributeOrderTask(taskId, orderId, orderContentDtoList);
                    } else {
                        distributeOrderTaskLogService.logError(taskId, orderId, "订单创建任务监听，订单商品为空112");
                    }
                }
            }
        }
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始定时处理订单分销结算任务：，耗时："+(endTime-startTime)+"毫秒");
    }
}